package com.project.controller;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.project.bean.FolloweBean;
import com.project.bean.PageBean;
import com.project.bean.UserBean;
import com.project.service.ICoachService;
import com.project.service.IFollowService;
import com.project.service.IGymService;
import com.project.service.IPostService;
import com.project.service.IStudentService;
import com.project.service.IUserService;
import com.project.util.DuanXin;
import com.project.util.UploadImgUtil;

@Controller
public class UserController {
	@Autowired
	private IUserService userservice;
	@Autowired
	private IStudentService stuservice;
	@Autowired
	private ICoachService coaservice;
	@Autowired
	private IGymService gymservice;
	@Autowired
	private IFollowService followservice;
	@Autowired 
	private IPostService postService;

 	@PostMapping("/login")
	public String login(String name, String pwd, ModelMap map, HttpSession session) {
		Subject currentuser = SecurityUtils.getSubject();
		if (!currentuser.isAuthenticated()) {
			UsernamePasswordToken token = new UsernamePasswordToken(name, pwd);
			try {
				currentuser.login(token);
				UserBean user = userservice.findUserByName(name);
				int type = user.getuType();
				map.put("username", name);
				session.setAttribute("type", type);
				session.setAttribute("username", name);
				session.setAttribute("UId", user.getuId());
				int id = user.getuId();
				System.out.println("登录角色的类型为" + type);
				System.out.println("角色的id:" + id);
				if (user.getuAddress() == null) {
					if (type == 1) {
						return "redirect:/student_info_change.html";
					}
					if (type == 2) {
						return "redirect:/coach_info_change.html";
					}
					if (type == 3) {
						return "redirect:/gym_info_change.html";
					}
				} else {
					return "redirect:/poster?id="+id+"&page=1&size=4";
				}
			} catch (Exception e) {
				System.out.println("异常不详：自己解决");
				return "redirect:/index.html";
			}
		}
		return "redirect:/index.html";
	}

	@RequestMapping("/changepassword")
	public String changepassword(String name, String pwd, String npwd) {
		System.out.println("账号:" + name);
		System.out.println("密码:" + pwd);
		System.out.println("新密码:" + npwd);
		UserBean user = userservice.findUserByName(name);
		// 将传入的账号 密码进行加密后判断是否和数据库的密码一样
		Object obj = new SimpleHash("MD5", pwd, name, 1024);
		String jpwd = obj.toString();
		System.out.println("原密码加密后的密码" + jpwd);
		System.out.println("数据库密码:" + user.getuPwd());
		if (user.getuPwd().equals(jpwd) == true) {
			Object obj1 = new SimpleHash("MD5", npwd, name, 1024);
			String npwd1 = obj1.toString();
			System.out.println("新密码加密后的密码" + npwd1);
			userservice.changeUserPassword(user.getuId(), npwd1);
		}
		return "redirect:/index.html";
	}

	@RequestMapping("/yanzhengma")
	@ResponseBody
	public String yanzhengma(String phonenumber) {

		return DuanXin.sendDuanXin(phonenumber);
	}

	@PostMapping("/reg")
	@ResponseBody
	public int regist(@Valid UserBean user, BindingResult result) {
		System.out.println("注册的类型为" + user.getuType());
		System.out.println("输入的验证码:" + user.getYanzhengma());
		System.out.println("后台的验证码:" + user.getSyanzhengma());
		if (result.hasErrors()) {
			// 获取全部错误信息
			Iterator<ObjectError> iterator = result.getAllErrors().iterator();
			while (iterator.hasNext()) {
				// 取出每一个错误
				ObjectError error = iterator.next();
				System.out.println("【错误信息】code = " + error.getCode() + "，message = " + error.getDefaultMessage());
				// return "redirect:/index.html";
				return 0;
			}
		}
		if (user.getYanzhengma().isEmpty()) {
			return 4;
		}
		if (user.getYanzhengma().equals(user.getSyanzhengma())) {
			UserBean user1 = new UserBean();
			user1 = userservice.findUserByName(user.getuUsername());
			if (user1 == null) {
				Object obj = new SimpleHash("MD5", user.getuPwd(), user.getuUsername(), 1024);
				user.setuPwd(obj.toString());
				// 用户注册
				userservice.registerUser(user);
				// 注册成功后在想对应的表添加一个对应的数据
				if (user.getuType() == 1) {
					stuservice.addStudentSUId(user.getuId());
				} else if (user.getuType() == 2) {
					coaservice.addCoachCUId(user.getuId());
				} else if (user.getuType() == 3) {
					gymservice.addGymGUId(user.getuId());
				}
				System.out.println(user);
				System.out.println("注册成功");
				// return "redirect:/index.html";
				return 3;
			} else {
				System.out.println("该账号已存在");
				// return "redirect:/index.html";
				return 2;
			}
		} else {
			return 1;
		}
	}

	@RequestMapping("/addusermessage")
	public String addUserMessage(String uName, String uAddress, String sRealname, int sAge, int sGender, Double uX,
			Double uY, MultipartFile ImgName, HttpSession session, HttpServletRequest req) {
		int UId = (int) session.getAttribute("UId");
		// 获取上传图片的名字
		String imgname = UploadImgUtil.uploadimg(req, ImgName);
		System.out.println(imgname);
		userservice.updateUserMessage(UId, uName, uAddress, imgname, uX, uY);
		stuservice.updateStudentMessage(sRealname, sAge, sGender, UId);
		return "redirect:poster?id="+UId+"&page=1&size=4";
	}

	@RequestMapping("/addcoachmessage")
	public String addStuMessage(String uName, String uAddress, String cRealname, int cAge, int cGender, int cSchool,
			Double uX, Double uY, MultipartFile ImgName, HttpSession session, HttpServletRequest req) {
		int UId = (int) session.getAttribute("UId");
		System.out.println(uName);
		System.out.println(ImgName);
		System.out.println(UId);
		// 获取上传图片的名字
		String imgname = UploadImgUtil.uploadimg(req, ImgName);
		System.out.println(imgname);
		userservice.updateUserMessage(UId, uName, uAddress, imgname, uX, uY);
		coaservice.updateCoachtMessage(cRealname, cAge, cGender, cSchool, UId);
		return "redirect:poster?id="+UId+"&page=1&size=4";
	}

	@RequestMapping("/addgymmessage")
	public String addGymMessage(String uName, String uAddress, String gMessage, Double uX, Double uY,
			MultipartFile ImgName, HttpSession session, HttpServletRequest req) {
		int UId = (int) session.getAttribute("UId");
		String imgname = UploadImgUtil.uploadimg(req, ImgName);
		userservice.updateUserMessage(UId, uName, uAddress, imgname, uX, uY);
		gymservice.updateGymMessage(UId, gMessage);
		return "redirect:poster?id="+UId+"&page=1&size=4";
	}

	@GetMapping("/judgeLogin")
	@ResponseBody
	public String judgeLogin(HttpServletRequest req) {
		HttpSession session = req.getSession();
		Object obj = session.getAttribute("Uid");
		if (obj != null) {
			int id=(int) obj;
			UserBean userBean=userservice.findUserById(id);
			return userBean.getuName();
		} else {
			return "";
		}

	}
	
	
	//用户取消关注
		@GetMapping("/quxiaogz")
		public String quxiaogz(int id,int page,int size,ModelMap map,HttpSession session){
			int a=(int) session.getAttribute("UId");
			followservice.deleteUserFollow(a, id);
			PageBean pageBean=postService.findUserPostsByPage(a, page, size);
			List<FolloweBean> list=followservice.findFollowsById(a);
			List<FolloweBean> listfan=followservice.findFansById(a);
			UserBean user=userservice.findUserById(a);
			System.out.println(user);
			map.addAttribute("lists", list);
			map.addAttribute("listfan",listfan);
			map.addAttribute("pageBean", pageBean);
			map.addAttribute("user", user);
			return "redirect:/poster？id="+a+"&page=1&size=4";
		}
		
		//用户关注
		@GetMapping("/guanzhu")
		public String guanzhu(int id,int page,int size,ModelMap map,HttpSession session){
			int a=(int) session.getAttribute("UId");
			System.out.println("被关注的id"+id);
			followservice.addFollow(a, id);
			PageBean pageBean=postService.findUserPostsByPage(a, page, size);
			List<FolloweBean> list=followservice.findFollowsById(a);
			List<FolloweBean> listfan=followservice.findFansById(a);
			UserBean user=userservice.findUserById(a);
			System.out.println(user);
			map.addAttribute("lists", list);
			map.addAttribute("listfan",listfan);
			map.addAttribute("pageBean", pageBean);
			map.addAttribute("user", user);
			return "redirect:/poster？id="+a+"&page=1&size=4";
		}	
		
	  //用户注销
	  @RequestMapping("/loginout")   
      public String zhuxiao(HttpSession session){ 
    	  session.invalidate();
    	  return "/index.html";
      }
	  @GetMapping("/judge_login")
		@ResponseBody
		public UserBean judge_login(HttpServletRequest req) {
			HttpSession session = req.getSession();
			Object obj = session.getAttribute("Uid");
			if (obj != null) {
				int id=(int) obj;
				UserBean userBean=userservice.findUserById(id);
				return userBean;
			} else {
				return null;
			}

		}
}
